﻿using System;
using System.Collections.Generic;
using System.IO;

namespace WPFCommon.FileManipulation
{
    public class FileHelper
    {
        /// <summary>
        /// Remove outdated files recursively if outdated
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="expireTimeSpan"></param>
        public static void RemoveOutdatedFiles(string dir, TimeSpan expireTimeSpan)
        {
            Directory.CreateDirectory(dir);
            foreach (string path in Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories))
            {
                var timeSpan = DateTime.Now - File.GetCreationTime(path);
                if(timeSpan > expireTimeSpan) File.Delete(path);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">file to create</param>
        /// <returns>Whether the file already exists</returns>
        public static bool CreateEmptyFileAndContainingFolder(string path)
        {
            if (File.Exists(path)) return true;

            // Create containing folder
            Directory.CreateDirectory(
                Path.GetDirectoryName(path) ?? throw new ArgumentException("Path can not be null"));
            // Create empty file
            File.Create(path).Dispose();

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fileLife"></param>
        /// <returns>Whether the file is successfully deleted</returns>
        public static bool RemoveOutdatedFile(string file, TimeSpan fileLife)
        {
            var timeSpan = DateTime.Now - File.GetCreationTime(file);
            if (timeSpan <= fileLife) return false;
            File.Delete(file);
            return true;

        }
        
        /// <summary>
        /// Append lines to file,
        /// if the file not exists create and append
        /// </summary>
        /// <param name="lines"></param>
        /// <param name="path"></param>
        /// <returns>Whether file already exists</returns>
        public static bool AppendLinesToFile(IList<string> lines, string path)
        {
            var fileExists = false;
            if (File.Exists(path))
            {
                fileExists = true;
            }
            else
            {
                CreateEmptyFileAndContainingFolder(path);
            }

            lines.Add(Environment.NewLine);
            File.AppendAllLines(path, lines);
            
            return fileExists;
        }
    }
}